/**
 * Trang ca nhan cua nguoi choi, cho phep thiet lap password, choi game, tao map, xoa map.
 */
package view;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import model.Constant;
import model.database.LevelDB;
import model.database.MapDB;
import model.database.PlayDB;
import model.database.UserDB;
import model.entity.Maps;
import model.entity.Playing;
import model.entity.User;
import view.drag.DragMapFrame;
import control.MD5Service;
import control.PlayingService;

/**
 * @author heroandtn3
 * @date Oct 22, 2012
 */
public class UserHomePanel extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public static final String KEY = "UserHomePanel";
    private MainPanel mainPanel;
    private User user;
    private PlayingService playSv = null;
    
    
    private JLabel lbHello;
    private JLabel lbYesNo;
    private JLabel lbSystem;
    private JLabel lbChangePassword;
    private JPanel userMenuPanel;
    private JLabel lbDelete;
    private JLabel lbNotice;
    private JLabel lbCountLevel;
    private JLabel lbImg;
    private JLabel lbPreview;
    private JLabel lbLevels;
    private JLabel lbType;
    private JLabel lbMapType;
    private JList<String> listMap;
    private JScrollPane scrollPane;
    private JLabel lbChoiceMap;
    private JScrollPane scrollTable;
    private JLabel lbChangeNotice;
    private JPasswordField tfNewPass;
    private JPasswordField tfOldPass;
    private JLabel lbChange;
    private JLabel lbNewPass;
    private JLabel lbOldPass;
    private JLabel lbCreate;
    private JLabel lbPlay;
    private JPanel gamePanel;
    private JLabel lbHighScore;
    private JTable tbHighScore;
    private JLabel lbSignout;
    private List<Maps> maps;
    private DefaultListModel<String> listMapModel;
    private DefaultTableModel tbHighScoreModel;
    private DragMapFrame dmf;

    public UserHomePanel(MainPanel mainPanel) {
        // TODO Auto-generated constructor stub
        this.mainPanel = mainPanel;
        initGUI();
        dmf = new DragMapFrame();
        dmf.setUserHome(this);
    }

    private void initGUI() {
        try {
            {
                this.setLayout(null);
                this.setPreferredSize(new java.awt.Dimension(900, 680));
                this.setBackground(new java.awt.Color(0,138,0));
                {
                	userMenuPanel = new JPanel();
                	userMenuPanel.setBackground(new java.awt.Color(0,138,0));
                	this.add(userMenuPanel);
                	userMenuPanel.setBounds(12, 34, 379, 605);
                	userMenuPanel.setBorder(BorderFactory.createTitledBorder(null, "User Menu", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(255,255,255)));
                	userMenuPanel.setLayout(null);
                	{
                		lbHello = new JLabel();
                		userMenuPanel.add(lbHello);
                		lbHello.setText("Hello");
                		lbHello.setBounds(17, 29, 112, 27);
                		lbHello.setFont(new java.awt.Font("Segoe UI",0,16));
                		lbHello.setForeground(new java.awt.Color(255,255,255));
                	}
                	{
                		lbHighScore = new JLabel();
                		userMenuPanel.add(lbHighScore);
                		lbHighScore.setText("High Score:");
                		lbHighScore.setBounds(17, 68, 112, 27);
                		lbHighScore.setFont(new java.awt.Font("Segoe UI",0,16));
                		lbHighScore.setForeground(new java.awt.Color(255,255,255));
                	}
                	{
                		lbSignout = new MyLabelButton(Constant.BUTTON_DIR + "signout", "Click to sign out", false);
                		userMenuPanel.add(lbSignout);
                		lbSignout.setBounds(314, 17, 48, 48);
                		lbSignout.addMouseListener(new MouseAdapter() {
                			public void mouseClicked(MouseEvent evt) {
                				//TODO add your code for lbSignout.mouseClicked
                				mainPanel.switchPanel("LoginPanel");
                			}
                		});
                	}
                	{
                		scrollTable = new JScrollPane();
                		userMenuPanel.add(scrollTable);
                		scrollTable.setBounds(17, 103, 345, 211);
                		{                                
                			tbHighScoreModel = new DefaultTableModel() {
                				/**
                				* 
                				*/
                				private static final long serialVersionUID = 1L;
                				
                				@Override
                				public boolean isCellEditable(int row, int column) {
                					// tat cac cac o deu khong duoc edit
                					return false;
                				}
                			};
                			tbHighScoreModel.addColumn("Date");
                			tbHighScoreModel.addColumn("Map");
                			tbHighScoreModel.addColumn("Level");
                			tbHighScoreModel.addColumn("Score");
                			
                			
                			tbHighScore = new JTable();
                			scrollTable.setViewportView(tbHighScore);
                			
                			tbHighScore.setModel(tbHighScoreModel);
                			tbHighScore.setBounds(35, 148, 291, 341);
                			tbHighScore.setPreferredSize(new java.awt.Dimension(327, 208));
                			
                		}
                	}
                	{
                		lbChangeNotice = new JLabel();
                		lbChangeNotice.setBounds(34, 519, 299, 47);
                		lbChangeNotice.setForeground(new java.awt.Color(255,0,0));
                	}
                	{
                		lbChange = new MyLabelButton(Constant.BUTTON_DIR + "ok", "Change password", false);
                		userMenuPanel.add(lbChange);
                		lbChange.setBounds(214, 503, 48, 48);
                		lbChange.addMouseListener(new MouseAdapter() {
                			public void mouseClicked(MouseEvent evt) {
                				//TODO add your code for lbChange.mouseClicked
                				String oldPass = new String(tfOldPass.getPassword());
                						String newPass = new String(tfNewPass.getPassword());
                						if (oldPass.length() <= 0 || newPass.length() <= 0) {
                							lbChangeNotice.setText("Some required fields is missing!");
                						} else if ((MD5Service.md5From(oldPass)).equals(user.getPassword())) {
                							
                							User newUser = new User(user.getName(), MD5Service.md5From(newPass));
                							UserDB uDB = new UserDB();
                							if (uDB.updateUser(user.getId(), newUser)) {
                								lbChangeNotice.setForeground(Color.GREEN);
                								lbChangeNotice.setText("Successfully changed!");
                							} else {
                								lbChangeNotice.setForeground(Color.RED);
                								lbChangeNotice.setText("Changed failure!");
                							}
                						} else {
                							lbChangeNotice.setText("Old password you entered does not match!");
                						}
                			}
                		});
                	}
                	{
                		tfNewPass = new JPasswordField();
                		userMenuPanel.add(tfNewPass);
                		tfNewPass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
                		tfNewPass.setBounds(187, 470, 111, 21);
                	}
                	{
                		tfOldPass = new JPasswordField();
                		tfOldPass.setBounds(187, 417, 111, 21);
                		userMenuPanel.add(tfOldPass);
                		tfOldPass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
                	}
                	{
                		lbOldPass = new JLabel();
                		lbOldPass.setBounds(44, 413, 113, 29);
                		userMenuPanel.add(lbOldPass);
                		lbOldPass.setText("Old Password");
                		lbOldPass.setFont(new java.awt.Font("Segoe UI",0,16));
                		lbOldPass.setForeground(new java.awt.Color(255,255,255));
                	}
                	{
                		lbNewPass = new JLabel();
                		lbNewPass.setBounds(44, 470, 113, 29);
                		userMenuPanel.add(lbNewPass);
                		lbNewPass.setText("New Password");
                		lbNewPass.setFont(new java.awt.Font("Segoe UI",0,16));
                		lbNewPass.setForeground(new java.awt.Color(255,255,255));
                	}
                	{
                		lbChangeNotice = new JLabel();
                		userMenuPanel.add(lbChangeNotice);
                		lbChangeNotice.setBounds(44, 560, 318, 34);
                	}
                	{
                		lbChangePassword = new JLabel();
                		userMenuPanel.add(lbChangePassword);
                		lbChangePassword.setText("Change Password:");
                		lbChangePassword.setBounds(44, 365, 131, 29);
                		lbChangePassword.setForeground(new java.awt.Color(255,255,255));
                		lbChangePassword.setFont(new java.awt.Font("Segoe UI",0,16));
                	}
                }
                {
                    gamePanel = new JPanel();
                    gamePanel.setBackground(new java.awt.Color(0,138,0));
                    this.add(gamePanel);
                    gamePanel.setLayout(null);
                    gamePanel.setBorder(BorderFactory.createTitledBorder(null, "Game", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(255,255,255)));
                    gamePanel.setBounds(403, 34, 485, 605);
                    {
                        lbPlay = new MyLabelButton(Constant.BUTTON_DIR + "play", "Play this map", false);
                        gamePanel.add(lbPlay);
                        lbPlay.setBounds(184, 494, 48, 48);
                        lbPlay.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                //TODO add your code for lbPlay.mouseClicked
                            	lbNotice.setText("");
                            	if (listMap.getSelectedIndex() > -1) {
                            		int mapID = maps.get(listMap.getSelectedIndex()).getId();
                            		mainPanel.getPlayPanel().resetGame();
                            		mainPanel.getPlayPanel().setPlaying(playSv.createPlaying(mapID));
                            		mainPanel.switchPanel(PlayPanel.KEY);
                            		mainPanel.getPlayPanel().getLvDlg().initListLevel();
                                    mainPanel.getPlayPanel().getLvDlg().setVisible(true);
                            	} else {
                            		lbNotice.setText("Please choose a map!");
                            	}
                            
                            }
                        });
                    }
                    {
                    	{
	                        lbCreate = new MyLabelButton(Constant.BUTTON_DIR + "create", "Create new map base this map", false);
	                        lbCreate.setBounds(295, 495, 48, 48);
	                        gamePanel.add(lbCreate);
	                        lbCreate.addMouseListener(new MouseAdapter() {
	                            public void mouseClicked(MouseEvent evt) {
	                                //TODO add your code for lbCreate.mouseClicked
	                            	lbNotice.setText("");
	                            	if (listMap.getSelectedIndex() > -1) {
	                            		Maps map = new Maps();
	                            		map.setImgDir(maps.get(listMap.getSelectedIndex()).getImgDir());
	                            		map.setUserCreateID(user.getId());
	                            		dmf.getSaveDlg().setMap(map);
	                            		dmf.pack();
	                            		dmf.setLocationRelativeTo(null);
	                            		dmf.setVisible(true);
	                            	} else {
	                            		lbNotice.setText("Please choose a map!");
	                            	}
	                            }
	                        });
                    	}
                        
                        
                        {
                        	lbDelete = new MyLabelButton(Constant.BUTTON_DIR + "delete", "Delete this map", false);
                        	gamePanel.add(lbDelete);
                        	lbDelete.setBounds(408, 495, 48, 48);
                        	lbDelete.addMouseListener(new MouseAdapter() {
                        		public void mouseClicked(MouseEvent evt) {
                        			//TODO add your code for lbDelete.mouseClicked
                        			lbNotice.setText("");
                        			if (listMap.getSelectedIndex() > -1) {
                        				Maps m = maps.get(listMap.getSelectedIndex());
                        				if (m.getUserCreateID() == 1) {
                        					lbNotice.setText("Cannot delete system map!");
                        				} else {
                        					MapDB mDB = new MapDB();
                            				if (mDB.deleteMapByID(m.getId())) {
                            					lbNotice.setText("Succesful delete");
                            					initHighScore();
                            					initListMap();
                            				} else {
                            					lbNotice.setText("Delete failure");
                            				}
                        				}
                        				
                        			} else {
                        				lbNotice.setText("Please choice a map!");
                        			}
                        			
                        			
                        		}
                        	});
                        }
                        {
                        	lbChoiceMap = new JLabel();
                        	gamePanel.add(lbChoiceMap);
                        	lbChoiceMap.setText("Choice Map");
                        	lbChoiceMap.setBounds(10, 36, 112, 27);
                        	lbChoiceMap.setForeground(new java.awt.Color(255,255,255));
                        	lbChoiceMap.setFont(new java.awt.Font("Segoe UI",0,16));
                        }
                        {
                        	scrollPane = new JScrollPane();
                        	gamePanel.add(scrollPane);
                        	scrollPane.setBounds(10, 69, 144, 512);
                        	{
                        		listMapModel = new DefaultListModel<String>();
                        		listMap = new JList<String>();
                        		scrollPane.setViewportView(listMap);
                        		listMap.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                        		listMap.setSelectedIndex(0);
                        		listMap.setModel(listMapModel);
                        		listMap.setBounds(18, 165, 124, 377);
                        		listMap.setPreferredSize(new java.awt.Dimension(141, 505));
                        		listMap.addListSelectionListener(new ListSelectionListener() {
                        			public void valueChanged(ListSelectionEvent evt) {
                        				//TODO add your code for listMap.valueChanged
                        				lbNotice.setText("");
                    					if (listMap.getSelectedIndex() > -1) {
                    						Maps tmp = maps.get(listMap.getSelectedIndex());
                    						lbType.setText(tmp.getImgDir());
                    						lbCountLevel.setText("" + new LevelDB().getCountLevelByMapID(tmp.getId()));
                    						lbImg.setIcon(new ImageIcon(Constant.MAP_DIR + tmp.getImgDir() + "/thumb"));
                    						if (tmp.getUserCreateID() == 1) { // kiem tra xem co phai la map system khong
                    							lbYesNo.setText("Yes");
                    						} else {
                    							lbYesNo.setText("No");
                    						}
                    					}
                        				
                        			}
                        		});
                        	}
                        }
                        {
                        	lbMapType = new JLabel();
                        	gamePanel.add(lbMapType);
                        	lbMapType.setText("Map Type:");
                        	lbMapType.setBounds(172, 69, 84, 24);
                        	lbMapType.setForeground(new java.awt.Color(255,255,255));
                        	lbMapType.setFont(new java.awt.Font("Segoe UI",0,16));
                        }
                        {
                        	lbType = new JLabel();
                        	gamePanel.add(lbType);
                        	lbType.setBounds(262, 70, 46, 23);
                        	lbType.setForeground(new java.awt.Color(255,255,255));
                        	lbType.setFont(new java.awt.Font("Segoe UI",0,16));
                        }
                        {
                        	lbLevels = new JLabel();
                        	gamePanel.add(lbLevels);
                        	lbLevels.setText("Number of levels:");
                        	lbLevels.setBounds(172, 112, 157, 24);
                        	lbLevels.setForeground(new java.awt.Color(255,255,255));
                        	lbLevels.setFont(new java.awt.Font("Segoe UI",0,16));
                        }
                        {
                        	lbPreview = new JLabel();
                        	gamePanel.add(lbPreview);
                        	lbPreview.setText("Preview:");
                        	lbPreview.setBounds(172, 149, 157, 24);
                        	lbPreview.setForeground(new java.awt.Color(255,255,255));
                        	lbPreview.setFont(new java.awt.Font("Segoe UI",0,16));
                        }
                        {
                        	lbImg = new JLabel();
                        	gamePanel.add(lbImg);
                        	lbImg.setBounds(172, 194, 296, 260);
                        }
                        {
                        	lbCountLevel = new JLabel();
                        	gamePanel.add(lbCountLevel);
                        	lbCountLevel.setBounds(353, 120, 95, 23);
                        	lbCountLevel.setForeground(new java.awt.Color(255,255,255));
                        	lbCountLevel.setFont(new java.awt.Font("Segoe UI",0,16));
                        }
                        {
                        	lbNotice = new JLabel();
                        	gamePanel.add(lbNotice);
                        	lbNotice.setBounds(172, 560, 296, 34);
                        	lbNotice.setForeground(Color.RED);
                        }
                        {
                        	lbSystem = new JLabel();
                        	gamePanel.add(lbSystem);
                        	lbSystem.setText("System:");
                        	lbSystem.setBounds(324, 69, 72, 24);
                        	lbSystem.setFont(new java.awt.Font("Segoe UI",0,16));
                        	lbSystem.setForeground(new java.awt.Color(255,255,255));
                        }
                        {
                        	lbYesNo = new JLabel();
                        	gamePanel.add(lbYesNo);
                        	lbYesNo.setBounds(408, 69, 60, 24);
                        	lbYesNo.setFont(new java.awt.Font("Segoe UI",0,16));
                        	lbYesNo.setForeground(new java.awt.Color(255,255,255));
                        }

                    }
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    } // ket thuc phuong thuc initGUI();
    
    /**
     * Tao danh sach cac map
     */
    public void initListMap() {
    	MapDB mDB = new MapDB();
		maps = mDB.getAllMapByUserCreateID(user.getId());
		listMapModel.clear();
		if (maps != null) {
			for (Maps map : maps) {
    			listMapModel.addElement(map.getName());
    		}
		}
		listMap.setSelectedIndex(0);
    }
    
    /**
     * Tao danh sach high score 
     */
    public void initHighScore() {
    	tbHighScoreModel.setRowCount(0);
    	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    	PlayDB pDB = new PlayDB();
    	List<Playing> plays = pDB.getAllPlayByUserID(user.getId());
    	for (Playing p : plays) {
    		String day = dateFormat.format(p.getDate());
    		String map = p.getMap().getName();
    		int level = p.getLevel();
    		int score = p.getScore();
    		tbHighScoreModel.addRow(new String[] {day, map, "" + level, score + ""});
    	}
    }
    

	/**
	 * @param playSv the playSv to set
	 */
	public void setPlaySv(PlayingService playSv) {
		this.playSv = playSv;
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

	/**
	 * @param user the user to set
	 */
	public void setUser(User user) {
		this.user = user;
		lbHello.setText("Hello " + user.getName() + ",");
	}
}